package com.cars.util.encrypt;

import java.util.Base64;

/**
 * 统一登录平台传输密码简便加密解密方法类
 *
 * @author dell
 * @date 2019-08-06
 */
public class Encryp {


    /**
     * 加密方法：根据random生成偏移量数组，待加密字符串根据偏移量数组进行字符偏移，全部偏移完成后，进行Base64加密返回。
     *
     * @param code   待加密字符串
     * @param random 偏移量数组的随机字符串（需要是全数字）
     * @return string 加密后的字符串
     */
    public static String en(String code, String random) {
        char[] chars = code.toCharArray();
        int[] indexs = indexs(random, chars.length);
        for (int i = 0; i < chars.length; i++) {
            int chari = chars[i];
            chars[i] = (char) (chari + Integer.valueOf(random.charAt(indexs[i])));
        }
        final Base64.Encoder encoder = Base64.getEncoder();
        String str = String.valueOf(chars);
        byte[] bytes = null;
        try {
            bytes = str.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String res = "";
        try {
            res = encoder.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 解密方法：先进行Base64解密，根据random获取偏移量，根据偏移量还原字符串
     *
     * @param code   待解密字符串
     * @param random 随机数（需要是全数字）
     * @return string 解密后的字符串
     */
    public static String de(String code, String random) {
        final Base64.Decoder decoder = Base64.getDecoder();
        String str = "";
        try {
            str = new String(decoder.decode(code), "UTF-8");
            char[] chars = str.toCharArray();
            int[] indexs = indexs(random, chars.length);
            for (int i = 0; i < chars.length; i++) {
                int chari = chars[i];
                chars[i] = (char) (chari - Integer.valueOf(random.charAt(indexs[i])));
            }
            str = String.valueOf(chars);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 根据random长度获取每个字符串的偏移量数组
     *
     * @param random 随机数
     * @param length 偏移量数组长度
     * @return int[] 偏移量数组
     */
    public static int[] indexs(String random, int length) {
        int[] indexs = new int[length];
        int rLength = random.length();
        for (int i = 0; i < indexs.length; i++) {
            indexs[i] = i % rLength;
        }
        return indexs;
    }

    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) {
        String enstr = Encryp.en("123456", "123451");
        String destr = Encryp.de(enstr, "123451");
        System.out.println(enstr);
        System.out.println(destr);
    }
}
